var Customer = {
    id: "CustomerTable",
    seItem: null,
    table: null,
    layerIndex: -1
};
var windowNameIndex = parent.layer.getFrameIndex(window.name); //获取窗口索引

function _formatter(value, row, index) {
    if (row.accountArrears > 0) {
        return '<span style="color: red" title="' + value + '">' + value + '</span>'
    } else {
        return '<span title="' + value + '">' + value + '</span>'
    }
}

function _formatterTime(value, row, index) {
    if (row.accountArrears > 0) {
        return "<span style='color: red'>" + value.substring(0, 19) + "</span>"
    } else {
        return value.substring(0, 19)
    }
}

Customer.initColumn = function () {
    var columns = [
        {field: 'selectItem',checkbox: true},
        {title: 'phones', field: 'phones', visible: false, align: 'center', valign: 'middle'},
        {title: 'deptAddress', field: 'deptAddress', visible: false, align: 'center', valign: 'middle'},
        {title: 'transportation', field: 'transportation', visible: false, align: 'center', valign: 'middle'},
        {title: 'startTime', field: 'startTime', visible: false, align: 'center', valign: 'middle'},
        {title: 'checkStatus', field: 'checkStatus', visible: false, align: 'center', valign: 'middle'},
        {title: 'id', field: 'id', visible: false, align: 'center', valign: 'middle'},
        {title: 'reservationsId', field: 'reservationsId', visible: false, align: 'center', valign: 'middle'},
        {title: '', field: 'customerSexHead ', visible: false, align: 'center', valign: 'middle'},
        {title: '病历号',field: 'medicalRecordNumber',align: 'center',valign: 'middle',sortable: true, width: 120,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '姓名',
            field: 'customerName',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 120,
            formatter: function (value, row, index) {
                if (row.accountArrears > 0) {
                    return "<a href='javascript:;' style='color: red;display: flex;align-items: center;' onclick = 'Customer.openBilee(" + '"' + row.id + '"' + ")' ><img src='" + row.customerSexHead + "' alt='' width='40px'><span class='portraitHeadName'>" + value + "</span></a>"
                } else {
                    return "<a href='javascript:;' style='display: flex;align-items: center;' onclick = 'Customer.openBilee(" + '"' + row.id + '"' + ")' ><img src='" + row.customerSexHead + "' alt='' width='40px'><span class='portraitHeadName'>" + value + "</span></a>"
                }
            }
        }, {
            title: '电话',
            field: 'customerPhone',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 140,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        },{
            title: '性别',
            field: 'sex',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 80,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '年龄',
            field: 'customerAge',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 80,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        } ,{
            title: '生日',
            field: 'birthday',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        },{
            title: '科室',
            field: 'treatmentUnit',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 80,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '一级渠道',
            field: 'oneChannel',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '二级渠道',
            field: 'twoChannel',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '三级渠道',
            field: 'thrChannel',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 130,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '客户状态',
            field: 'customerStatus',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '开单状态',
            field: 'dealStatus',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 110,
            formatter: function (value, row, index) {
                if (value === "已结账") {
                    if (row.accountArrears > 0) {
                        return "<a href='javascript:;' style='color: red' onclick='Customer.opendealStatus(" + '"' + row.reservationsId + '"' + ")'>[已结账]</a>"
                    } else {
                        return "<a href='javascript:;' onclick='Customer.opendealStatus(" + '"' + row.reservationsId + '"' + ")'>[已结账]</a>"
                    }
                } else if (value !== "已结账") {
                    return _formatter(value, row, index)
                }
            }
        }, {
            title: '已交金额',
            field: 'actualAccountBalance',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 110,
            formatter: function (value, row, index) {
                if (row.accountArrears > 0) {
                    return "<a href='javascript:;' style='color: red'>" + (value + row.moneyBalance) + "</a>"
                } else {
                    return (value + row.moneyBalance)
                }
            }
        }, {
            title: '欠费',
            field: 'accountArrears',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '现场TC',
            field: 'fieldTc',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '医生',
            field: 'doctor',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '到店时间',
            field: 'arrivalTime',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 170,
            formatter: function (value, row, index) {
                return _formatterTime(value, row, index)
            }
        }, {
            title: '初诊时间',
            field: 'firstVisitDate',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '黄页编号',
            field: 'yellowNumber',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 140,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '备注',
            field: 'remarks',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 120,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            },
            cellStyle: function (value, row, index) {
                return {css: {"overflow": "hidden", "white-space": "nowrap", "text-overflow": "ellipsis"}}
            }
        }, {
            title: '网电咨询师',
            field: 'scarchiving',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 130,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '一级媒介',
            field: 'oneMedium',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 130,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '二级媒介',
            field: 'twoMedium',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 130,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }, {
            title: '三级媒介',
            field: 'thrMedium',
            align: 'center',
            valign: 'middle',
            sortable: true,
            width: 130,
            formatter: function (value, row, index) {
                return _formatter(value, row, index)
            }
        }];
    return columns
};

Customer.choiceTc = function (id) {
    $.ajax({
        url: Feng.ctxPath + "/customer/getCustomerIsDealStatus/" + id,
        type: "post",
        success: function (data) {
            if (data == 1) {
                alert("此患者已开单不能修改TC！");
                return
            } else {
                var index = layer.open({
                    type: 2,
                    title: '选择Tc',
                    area: ['50%', '60%'],
                    fix: true,
                    maxmin: true,
                    content: Feng.ctxPath + '/customer/to_choiceTc/' + id
                });
                this.layerIndex = index
            }
        },
        error: function (data) {
            alert('没有权限，请联系系统管理员!');
            parent.layer.close(windowNameIndex)
        }
    })
};

Customer.openBilee = function (ide) {
    $.ajax({
        url: Feng.ctxPath + "/consultantTwo/getdcsByCustomerId",
        type: "post",
        data: {
            "id": ide
        },
        success: function (data) {
            if (data == 1) {
                var index = layer.open({
                    type: 2,
                    title: '到店客户详情',
                    area: ['100%', '100%'],
                    fix: true,
                    maxmin: true,
                    content: Feng.ctxPath + '/customerDetails/to_openBileLists/' + ide + "/0"
                });
                this.layerIndex = index
            } else {
                alert("请先联系前台客服匹配建档！");
                return
            }
        }
    })
};

var parseParam = function (param) {
    var paramStr = "";
    $.each(param, function (i) {
        paramStr += '&' + getSingleData(param, i)
    });
    return paramStr.substr(1)
};
var getSingleData = function (param, key) {
    return key + "=" + param[key]
};

Customer.upload = function () {
    var index = layer.open({
        type: 2,
        title: '导入',
        area: ['70%', '80%'],
        fix: true,
        maxmin: true,
        content: Feng.ctxPath + '/customerUpload/customer_import'
    });
    this.layerIndex = index
};

Customer.downLoad = function () {
    var queryData = {};
    queryData['sreach'] = $("#sreach").val();
    queryData['startArrivalTime'] = $("#startArrivalTime").val();
    queryData['endArrivalTime'] = $("#endArrivalTime").val();
    queryData['fieldTc'] = $("#fieldTc").val();
    queryData['doctor'] = $("#doctor").val();
    queryData['dealStatus'] = $("#dealStatus").val();
    queryData['oneChannel'] = multipleSelection($('#oneChannel').val());
    queryData['twoChannel'] = multipleSelection($('#twoChannel').val());
    queryData['thrChannel'] = multipleSelection($('#thrChannel').val());
    queryData['customerStatus'] = $("#customerStatus").val();
    var param = parseParam(queryData);
    location.href = Feng.ctxPath + '/customer/customerExport?' + param
};

Customer.resetSearch = function () {
    $("#sreach").val("");
    $("#customerName").val("");
    $("#customerPhone").val("");
    $("#startArrivalTime").val("");
    $("#endArrivalTime").val("");
    $("#reservations").val("");
    $("#startRevisitTime").val("");
    $("#endRevisitTime").val("");
    $("#fieldTc").val("");
    $("#doctor").val("");
    $("#customerStatus").val("");
    $("#dealStatus").val("");
    $('#oneChannel').selectpicker('val', ['noneSelectedText']);
    $('#twoChannel').selectpicker('val', ['noneSelectedText']);
    $('#thrChannel').selectpicker('val', ['noneSelectedText']);
    $(".timeBox > div button").removeClass('actionClick');
    Customer.search()
};

Customer.opendealStatus = function (id) {
    $.ajax({
        url: Feng.ctxPath + "/reservations/getTotleMoneys",
        type: "post",
        data: {
            "id": id
        },
        success: function (data) {
            alert("成交金额：" + data + "元")
        },
        error: function (data) {
            alert('没有权限，请联系系统管理员!');
            parent.layer.close(windowNameIndex)
        }
    })
};

Customer.inputInfo = function () {
    var index = layer.open({
        type: 2,
        title: '批量上传',
        area: ['90%', '90%'],
        maxmin: true,
        content: Feng.ctxPath + '/recharge/customerInfo_import/'
    });
    this.layerIndex = index
};

Customer.shortMessage = function () {
    var dataList  = [];
    var numberList = $("#CustomerTable").bootstrapTable('getSelections');
    for (var i = 0; i < numberList.length; i++) {
        var obj = {
            id:numberList[i].id,
            customerName:numberList[i].customerName,
            customerPhone:numberList[i].customerPhone,
            time:numberList[i].startTime.substring(0, 19),
            outpatientName:numberList[i].arrivalStore,
            deptAddress:numberList[i].deptAddress,
            phones:numberList[i].phones,
            transportation:numberList[i].transportation
        };
        dataList.push(obj);
    }
    sessionStorage.setItem("dataList", JSON.stringify(dataList));
    if (this.check()) {
        var customerId = Customer.seItem.id;
        var index = layer.open({
            type: 2,
            title: '发送消息',
            area: ['60%', '80%'],
            fix: true,
            maxmin: true,
            content: Feng.ctxPath + '/msgSend/to_msgSend2/' + customerId
        });
        this.layerIndex = index
    }
};
Customer.updateTochoiceTc = function () {
    if (this.check()) {
        var id = Customer.seItem.id;
        $.ajax({
            url: Feng.ctxPath + "/customer/getCustomerIsDealStatus/" + id,
            type: "post",
            success: function (data) {
                if (data == 1) {
                    alert("此患者已开单不能修改TC！");
                    return
                } else {
                    var index = layer.open({
                        type: 2,
                        title: '选择Tc',
                        area: ['50%', '60%'],
                        fix: true,
                        maxmin: true,
                        content: Feng.ctxPath + '/customer/to_choiceTc/' + id
                    });
                    this.layerIndex = index
                }
            },
            error: function (data) {
                alert('没有权限，请联系系统管理员!');
                parent.layer.close(windowNameIndex)
            }
        })
    }
};
Customer.msgSendTwo = function () {
    var dataList = JSON.parse(sessionStorage.getItem("dataList"));
    var messageData = {
        messageContent:$('#message_content').val(),
        templateCode:$("#templateCodeValue").val(),
        smsParameterId:$("#smsParameterId").val(),
        patientList:dataList
    };
    if($("#message_content").val() == ""){
        Feng.error("请选择短信模板");
        return ;
    }
    $.ajax({
        url: Feng.ctxPath + "/msgSend/msgSend2",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(messageData),
        success: function (data) {
            Feng.success('操作成功!');
            Customer.close();
        },
        error: function (data) {
            alert('没有权限，请联系管理员!');
        }
    });
};

Customer.sendMedicalAdvice = function () {
    var customerPhone = $("#customerPhone").val();
    var index = layer.open({
        type: 2,
        title: '诉后医嘱',
        area: ['70%', '80%'],
        fix: true,
        maxmin: true,
        content: Feng.ctxPath + '/customer/to_sendMedicalAdvice/' + customerPhone
    });
    this.layerIndex = index
};

Customer.openBilee = function (ide) {
    $.ajax({
        url: Feng.ctxPath + "/consultantTwo/getdcsByCustomerId",
        type: "post",
        data: {
            "id": ide
        },
        success: function (data) {
            if (data == 1) {
                var index = layer.open({
                    type: 2,
                    title: '到店客户详情',
                    area: ['100%', '100%'],
                    fix: true,
                    maxmin: true,
                    content: Feng.ctxPath + '/customerDetails/to_openBileLists/' + ide + "/0"
                });
                this.layerIndex = index
            } else {
                alert("请先联系前台客服匹配建档！");
                return
            }
        }
    })
};

Customer.dealUpload = function () {
    var index = layer.open({
        type: 2,
        title: '开单数据',
        area: ['70%', '80%'],
        fix: true,
        maxmin: true,
        content: Feng.ctxPath + '/recharge/dealInfo_import/'
    });
    this.layerIndex = index
};

Customer.to_generateQrCode = function () {
    if (this.check()) {
        var id = Customer.seItem.id;
        var reservationsId = Customer.seItem.reservationsId;
        $.ajax({
            url: Feng.ctxPath + "/customer/getMemberStatus",
            type: "post",
            data: {
                "reservationsId": reservationsId
            },
            success: function (data) {
                if (data == 1) {
                    var index = layer.open({
                        type: 2,
                        title: '&nbsp',
                        area: ['70%', '80%'],
                        fix: true,
                        maxmin: true,
                        content: Feng.ctxPath + '/customer/to_generateQrCode/' + id
                    });
                    this.layerIndex = index
                } else {
                    alert("已经扫码注册了！");
                    return
                }
            }
        })
    }
};

Customer.openBillingJY = function () {
    if (this.check()) {
        var customerId = Customer.seItem.id;
        var index = layer.open({
            type: 2,
            title: '&nbsp',
            area: ['100%', '100%'],
            fix: true,
            maxmin: true,
            content: Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + customerId + '/2/0'
        });
        this.layerIndex = index
    }
};

Customer.addTreatmentUnit = function () {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '增加科室',
            area: ['60%', '50%'],
            fix: true,
            maxmin: true,
            content: Feng.ctxPath + '/customer/add_TreatmentUnit/' + Customer.seItem.id
        });
        this.layerIndex = index
    }
};

Customer.close = function () {
    parent.layer.close(windowNameIndex)
};

Customer.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        Feng.info("请先选中表格中的某一记录！");
        return false
    } else {
        Customer.seItem = selected[0];
        return true
    }
};

Customer.search = function () {
    Customer.table.refresh({
        query: Customer.formParams()
    });
};

Customer.naturalDaySearch = function (obj) {
    if (obj == 1) {
        $("#startArrivalTime").val(setDateTime(new Date(), 0) + " 00:00:00");
        $("#endArrivalTime").val(setDateTime(new Date(), 0) + " 23:59:59");
        $(".timeBox > div button").eq(0).addClass('actionClick').siblings().removeClass('actionClick')
    } else if (obj == 2) {
        var AccountsTime = $("#sttleAccountsTime").val();
        $("#startArrivalTime").val(setDateTime(new Date(), 1) + " " + AccountsTime);
        $("#endArrivalTime").val(setDateTime(new Date(), 0) + " " + AccountsTime);
        $(".timeBox > div button").eq(1).addClass('actionClick').siblings().removeClass('actionClick')
    }
    ;
    Customer.search();
};

Customer.formParams = function () {
    var queryData = {};
    queryData['sreach'] = $("#sreach").val();
    queryData['customerName'] = $("#customerName").val();
    queryData['customerPhone'] = $("#customerPhone").val();
    queryData['startArrivalTime'] = $("#startArrivalTime").val();
    queryData['endArrivalTime'] = $("#endArrivalTime").val();
    queryData['reservations'] = $("#reservations").val();
    queryData['startRevisitTime'] = $("#startRevisitTime").val();
    queryData['endRevisitTime'] = $("#endRevisitTime").val();
    queryData['fieldTc'] = $("#fieldTc").val();
    queryData['doctor'] = $("#doctor").val();
    queryData['dealStatus'] = $("#dealStatus").val();
    queryData['customerStatus'] = $("#customerStatus").val();
    queryData['treatmentUnit'] = $("#treatmentUnit").val();
    queryData['oneChannel'] = multipleSelection($('#oneChannel').val());
    queryData['twoChannel'] = multipleSelection($('#twoChannel').val());
    queryData['thrChannel'] = multipleSelection($('#thrChannel').val());
    queryData['abbreviation'] = $("#abbreviation", parent.document).val();
    queryData['outpatientName'] = $("#outpatientName", parent.document).val();
    queryData['birthday'] = $("#birthday").val();
    return queryData
};

Customer.birthdaySearch = function () {
    var date = new Date();
    var date2 = new Date(date.getTime());
    var month = date2.getMonth()+1;
    var date1 = date2.getDate();
    if(month<10){
        month = "0"+month;
    }
    if(date1<10){
        date1 = "0"+date1;
    }
    var str1 = month+"-"+date1;
    $("#birthday").val(str1);
    $("#startArrivalTime").val("");
    $("#endArrivalTime").val("");
    Customer.search();
};

function phonePrivileges(){   //隐藏手机号
    var phonePrivileges=parent.$("#phonePrivileges").val();
    if(phonePrivileges == 2){
        $('#CustomerTable').bootstrapTable('hideColumn', 'customerPhone');
    }
}

function setRegular(targetHour){
    var timeInterval,nowTime,nowSeconds,targetSeconds
    nowTime = new Date()
    // 计算当前时间的秒数
    nowSeconds = nowTime.getHours() * 3600 + nowTime.getMinutes() * 60 + nowTime.getSeconds()
    // 计算目标时间对应的秒数
    targetSeconds =  targetHour * 3600
    //  判断是否已超过今日目标小时，若超过，时间间隔设置为距离明天目标小时的距离
    timeInterval = targetSeconds > nowSeconds ? targetSeconds - nowSeconds: targetSeconds + 24 * 3600 - nowSeconds
    setTimeout(getProductFileList,timeInterval * 1000)
}

function getProductFileList(){
    var date = new Date();
    var date2 = new Date(date.getTime());
    var month = date2.getMonth()+1;
    var date1 = date2.getDate();
    if(month<10){
        month = "0"+month;
    }
    if(date1<10){
        date1 = "0"+date1;
    }
    var time = month+"-"+date1;
    $.ajax({
        url: Feng.ctxPath + "/msgSend/msgSendAotu",
        type: "post",
        data: {
            "time": time
        },
        success: function (data) {
            if (data == 1) {
                Feng.success('操作成功!');
            }
        }, error: function (data) {
            alert('没有权限，请联系管理员!');
        }
    })
    setTimeout(getProductFileList,24*3600 * 1000)//之后每天调用一次
}
setRegular(11);//比如目标是每天14点


$(function () {
    var defaultColunms = Customer.initColumn();
    var table = new BSTable(Customer.id, "/customer/qfList", defaultColunms);
    table.setPaginationType("server");
    table.setQueryParams(Customer.formParams());
    Customer.table = table.init();
    Customer.naturalDaySearch(1);
    menuNameHideColumn($("#menuName").val(), 'CustomerTable');
    $("#oneChannel").change(function () {
        $("#twoChannel").val('请选择');
        $("#thrChannel").val('请选择');
        Customer.search();
    });
    $("#twoChannel").change(function () {
        $("#thrChannel").val('请选择');
        Customer.search();
    });
    $("#thrChannel").change(function () {
        Customer.search();
    });
    $(document).on('click', '#laydate_clear,#laydate_today,#laydate_ok', function () {
        Customer.search();
    });
    checkDate = function () {
        Customer.search();
    };
    phonePrivileges();
});
